import { reactive, computed } from 'vue'
import type { PropertyPanelProps, AssigneeConfig, ButtonConfig, ButtonType } from '../types'
import type Modeling from 'bpmn-js/lib/features/modeling/Modeling'
import type { Moddle } from 'bpmn-moddle'
import { useButtonConfig } from './useButtonConfig'

export function useAssigneeConfig(props: PropertyPanelProps) {
  const { buttonTypeOptions } = useButtonConfig()

  // 初始化所有可用按钮
  const initButtons = (): ButtonConfig[] => {
    return buttonTypeOptions.map((option, index) => ({
      id: `btn_${option.value}`,
      name: option.label,
      type: option.value as ButtonType,
      sort: index + 1,
      enabled: false,
    }))
  }

  const assigneeConfig = reactive<AssigneeConfig>({
    emptyStrategy: 'specified_user',
    assigneeType: 'user',
    assigneeValue: '',
    buttons: initButtons(),
  })

  // 是否显示代办人配置
  const showAssigneeConfig = computed(() => {
    return props.currentElement?.type === 'bpmn:UserTask'
  })

  // 空审批人策略选项
  const emptyStrategyOptions = [
    { label: '指定成员审批', value: 'specified_user' },
    { label: '自动通过', value: 'auto_pass' },
    { label: '自动拒绝', value: 'auto_reject' },
  ]

  // 代办人类型选项
  const assigneeTypeOptions = [
    { label: '用户', value: 'user' },
    { label: '角色', value: 'role' },
    { label: '用户组', value: 'group' },
    { label: '岗位', value: 'position' },
    { label: '表达式', value: 'expression' },
  ]

  // 处理按钮启用状态变更
  const handleButtonStatusChange = (button: ButtonConfig) => {
    console.log('button-after', button.enabled)
    handleAssigneeChange()
  }

  // 修改处理代办人配置变更函数
  const handleAssigneeChange = () => {
    if (!props.currentElement || !props.modeler) return

    const modeling = props.modeler.get('modeling') as Modeling
    const moddle = props.modeler.get('moddle') as Moddle
    const { emptyStrategy, assigneeType, assigneeValue, buttons } = assigneeConfig

    // 只保存启用的按钮
    const enabledButtons = buttons.filter((btn) => btn.enabled)
    const buttonElements = enabledButtons.map((button) => {
      return moddle.create('flowable:ButtonConfig', {
        id: button.id,
        name: button.name,
        type: button.type,
        sort: button.sort,
        enabled: button.enabled,
      })
    })

    // 获取或创建扩展元素
    let extensionElements = props.currentElement.businessObject.extensionElements
    if (!extensionElements) {
      extensionElements = moddle.create('bpmn:ExtensionElements', { values: [] })
    }

    // 过滤掉旧的按钮配置
    const otherElements =
      extensionElements.values?.filter((item: any) => item.$type !== 'flowable:ButtonConfig') || []

    // 更新扩展元素
    extensionElements.values = [...otherElements, ...buttonElements]

    // 更新属性
    modeling.updateProperties(props.currentElement, {
      'flowable:emptyStrategy': emptyStrategy,
      'flowable:assigneeType': assigneeType,
      'flowable:assigneeValue': assigneeValue,
      extensionElements,
    })
  }

  // 修改监听当前元素变化的逻辑
  if (props.currentElement?.type === 'bpmn:UserTask') {
    const bo = props.currentElement.businessObject
    assigneeConfig.emptyStrategy = bo.get('flowable:emptyStrategy') || 'specified_user'
    assigneeConfig.assigneeType = bo.get('flowable:assigneeType') || 'user'
    assigneeConfig.assigneeValue = bo.get('flowable:assigneeValue') || ''

    // 重置所有按钮状态
    assigneeConfig.buttons = initButtons()

    // 获取已配置的按钮
    const extensionElements = bo.extensionElements
    if (extensionElements && extensionElements.values) {
      const buttonConfigs = extensionElements.values.filter(
        (item: any) => item.$type === 'flowable:ButtonConfig',
      )

      // 更新已配置按钮的状态
      buttonConfigs.forEach((config: any) => {
        const button = assigneeConfig.buttons.find((btn) => btn.type === config.type)
        if (button) {
          button.enabled = true
          button.name = config.name
          button.sort = config.sort
        }
      })
    }
  }

  return {
    assigneeConfig,
    showAssigneeConfig,
    emptyStrategyOptions,
    assigneeTypeOptions,
    buttonTypeOptions,
    handleAssigneeChange,
    handleButtonStatusChange,
  }
}
